package com.wanboedu.controller;

import com.wanboedu.constant.JwtClaimsConstant;
import com.wanboedu.dto.UserDTO;
import com.wanboedu.properties.JwtProperties;
import com.wanboedu.result.Result;
import com.wanboedu.service.UserService;
import com.wanboedu.utils.JwtUtil;
import com.wanboedu.vo.UserVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/login")
@Slf4j
@Api("登录接口")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping()
    public Result login(@RequestBody UserDTO userDTO) {
        log.info("登录用户", userDTO);
        UserVO user = userService.login(userDTO);
        System.out.println(user.toString());
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        UserVO userVO = UserVO.builder()
                .id(user.getId())
                .account(user.getAccount())
                .name(user.getName())
                .password("******")
                .token(token)
                .build();

        return Result.success(userVO);
    }
}
